<?php

namespace app\admin\controller\form;

use app\admin\model\Form;
use app\common\controller\Backend;
use think\Db;

/**
 * 
 *
 * @icon fa fa-wpforms
 */
class Data extends Backend
{
    
    /**
     * FormData模型对象
     */
    protected $model = null;

    protected $tableTitle = null;

    public function _initialize()
    {
        parent::_initialize();

        // 数据列表
        $all = collection(Form::select())->toArray();
        $formList = [];
        $tableTitleArray = array();

        foreach ($all as $k => $v)
        {
            $state = ['opened' => true];

            if($k == 0){
                $state['selected'] = true;
            }
            $formList[] = [
                'id'     => $v['id'],
                'parent' => '#',
                'text'   => __($v['name']),
                'type'   => 'page',
                'state'  => $state
            ];

            $data = Db::name('form_'.$v['table'])->limit(1)->select();
            $tableTitle = array_keys($data[0]);
            $tableTitleArray[$v['id']] = $tableTitle;
        }

        $this->assignconfig('formList', $formList);
        $this->assignconfig('tableTitle', $tableTitleArray);
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            $param = input();

            if($param['filter'] != '{}'){
                $formId = json_decode($param['filter'])->form_id;
            }else{
                $formId = 1;
            }

            $formTable = Form::where('id', 'IN', $formId)->field('table')->find()->toArray();

            $this->relationSearch = TRUE;
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparamsFormData();

            $total = Db::name('form_'.$formTable['table'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();

            $list = Db::name('form_'.$formTable['table'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function getTableTitle()
    {
        return json($this->tableTitle);
    }
}
